package com.google.code.porntube.snap.core.io;

import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.code.porntube.snap.result.Clip;

public final class Store {
	
	private static DatastoreService datastore;	
	
	static {
		datastore = DatastoreServiceFactory.getDatastoreService();
	}
	
	public static Clip pop() {
		Clip clip = null;
		Query query = new Query("Clip").addSort("update", SortDirection.ASCENDING);
		PreparedQuery preparedQuery = datastore.prepare(query);
		
		List<Entity> entities = preparedQuery.asList(FetchOptions.Builder.withLimit(1));
		if(entities.size() > 0) {
			Entity entity = entities.get(0);
			clip = new Clip();
			clip.setId(entity.getKey().getId());
			clip.setCatalog((String) entity.getProperty("catalog"));
			clip.setDuration((String) entity.getProperty("duration"));
			clip.setFile((String) entity.getProperty("file"));
			clip.setName((String) entity.getProperty("name"));
			clip.setTag((String) entity.getProperty("tag"));
			clip.setThumbnail((String) entity.getProperty("thumbnail"));
			clip.setUpdate((Date) entity.getProperty("update"));
			clip.setUrl((String) entity.getProperty("url"));
			clip.setConfig((String) entity.getProperty("config"));
		}
		return clip;
	}
	
	public static void push(Clip target) {
		Entity clip = new Entity("Clip");
		clip.setProperty("name", target.getName());
		clip.setProperty("url", target.getUrl());
		clip.setProperty("catalog", target.getCatalog());
		clip.setProperty("tag", target.getTag());
		clip.setProperty("duration", target.getDuration());
		clip.setProperty("file", target.getFile());
		clip.setProperty("thumbnail", target.getThumbnail());
		clip.setProperty("config", target.getConfig());
		clip.setProperty("update", target.getUpdate());		
		clip.setProperty("push", new Date());
		datastore.put(clip);
	}
	
	public static void remove(String id) {
		Key k = KeyFactory.createKey("Clip", Integer.valueOf(id));
		datastore.delete(k);
	}
			
}
